package com.kotlin.demo.tools

import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle

/**
 * 组件工具类
 */
object UiUtils {
    // 格式化并为 JSON 数据添加颜色的函数
    fun formatAndColorizeJson(json: String): AnnotatedString {
        return buildAnnotatedString {
            var inString = false
            var inKey = false
            var escape = false
            for (i in json.indices) {
                val char = json[i]
                when {
                    escape -> {
                        append(char)
                        escape = false
                    }
                    char == '\\' -> {
                        append(char)
                        escape = true
                    }
                    char == '"' -> {
                        append(char)
                        if (!escape) {
                            inString = !inString
                            inKey = !inKey && inString
                        }
                    }
                    inString -> {
                        withStyle(style = SpanStyle(color = Color(0xFF008000))) {
                            append(char)
                        }
                    }
                    char in listOf('{', '}', '[', ']', ',', ':') -> {
                        withStyle(style = SpanStyle(color = Color(0xFFFF0000))) {
                            append(char)
                        }
                    }
                    inKey -> {
                        withStyle(style = SpanStyle(color = Color(0xFFFFFF99))) {
                            append(char)
                        }
                    }
                    else -> {
                        append(char)
                    }
                }
            }
        }
    }
}